<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use App\Internals\StudyInternal;
use App\Internals\CourseInternal;
use App\Jobs\LessonStartJob;

class WechatPushLessonBeingSendCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:wechat-push-lesson-being-send';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'The wechat push of lesson being send';

    protected $courseLessonsArr = [];
    protected $courseInfoArr = [];

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        Log::info('lesson-being-send start');
        try {
            $time=microtime(true);
            $page = 1;
            $limit = 100;
            $courseEnd = [];

            // 获取所有用户当前正在学习的课程
            while($currents = StudyInternal::getAllUsersCurrent(false, $page, $limit)) {
                Log::info('$currents: ' . var_export($currents, true));
                if (! count($currents)) {
                    break;
                }

                foreach($currents as $current) {
                    $userId = $current['userId'];
                    $courseId = $current['courseId'];

                    // 获取课程所有的lesson信息
                    $courseLessons = $this->getCourseLessons($courseId);
                    Log::info('$courseLessons: ' . var_export($courseLessons, true));
                    if (! $courseLessons) {
                        continue;
                    }

                    // 获取用户最近的lesson信息
                    $lesson = StudyInternal::getLatestLessonByUserIdCourseId($userId, $courseId);
                    // 获取最新将要推送的lesson信息
                    $newLesson = $this->nextCourseLesson($courseLessons, $lesson ? $lesson['sequence'] : 0);
                    Log::info('$newLesson: ' . var_export($newLesson, true));
                    if (! $newLesson) {
                        continue;
                    }

                    // 获取course信息
                    $courseInfo = $this->getCourseInfo($courseId);
                    Log::info('$courseInfo: ' . var_export($courseInfo, true));
                    if (! $courseInfo) {
                        continue;
                    }

                    $enableTime = app()->environment('production') ? date('Y-m-d 20:00:00') : date('Y-m-d H:i:s');

                    // 保存最新lesson信息到user_lessons表
                    $res = StudyInternal::lessonStore([
                        'userId'         => $userId,
                        'lessonId'       => $newLesson['id'],
                        'courseId'       => $courseId,
                        'sequence'       => $newLesson['sequence'],
                        'wordCount'      => $newLesson['wordCount'],
                        'knowledgeCount' => $newLesson['knowledgeCount'],
                        'essenceQaCount' => $newLesson['essenceQaCount'],
                        'gameTestCount'  => $newLesson['gameTestCount'],
                        'gameWordCount'  => $newLesson['gameWordCount'],
                        'enableTime'     => $enableTime,
                    ]);
                    if (! $res) {
                        continue;
                    }
                    Log::info('lessonStore success');

                    dispatch(new LessonStartJob(
                        $userId,
                        $newLesson['name'],
                        $newLesson['sequence'],
                        $courseInfo['level'],
                        date('Y-m-d 20:00'),
                        $courseInfo['seriesName']
                    ));
                    Log::info('LessonStartJob: ' . var_export([
                        $userId,
                        $newLesson['name'],
                        $newLesson['sequence'],
                        $courseInfo['level'],
                        date('Y-m-d 20:00'),
                        $courseInfo['seriesName']
                    ], true));

                    // 检查课时是否已经都推送完
                    if ($courseInfo['lessonCount'] <= count($courseLessons)) {
                        if ($newLesson['id'] == end($courseLessons)['id']) {
                            $courseEnd[] = [
                                'userId' => $userId,
                                'courseId' => $courseId,
                            ];
                        }
                    }
                }
                $page++;
            }
            foreach ($courseEnd as $v) {
                StudyInternal::setCoursePushEnd($v['userId'], $v['courseId']);
            }

            Log::info('lesson-being-send cost: '. (microtime(true)-$time));
        } catch (\Exception $e) {
            var_dump($e->getMessage());
            Log::info('lesson-being-send failed: ' . $e->getMessage());
        }
    }

    // 获取课程所有的lesson信息
    private function getCourseLessons($courseId)
    {
        if (isset($this->courseLessonsArr[$courseId])) {
            $courseLessons = $this->courseLessonsArr[$courseId];
        } else {
            $courseLessons = CourseInternal::getCourseLessons($courseId);
            if($courseLessons) {
                $courseLessons = $this->array_using_key($courseLessons, 'sequence');
                $this->courseLessonsArr[$courseId] = $courseLessons;
            }
        }

        return $courseLessons;
    }

    private function array_using_key($arr, $field)
    {
        return array_combine(array_values(array_column($arr, $field)), $arr);
    }

    // 获取course信息
    private function getCourseInfo($courseId)
    {
        if (isset($this->courseInfoArr[$courseId])) {
            $courseInfo = $this->courseInfoArr[$courseId];
        } else {
            $courseInfo = CourseInternal::getCourse($courseId);
            if($courseInfo) {
                $this->courseInfoArr[$courseId] = $courseInfo;
            }
        }

        return $courseInfo;
    }

    private function nextCourseLesson($lessons, $sequence)
    {
        return isset($lessons[$sequence+1]) ? $lessons[$sequence+1] : [];
    }

}
